package org.deltaset.faces.module;

import java.net.URL;
import javax.faces.view.facelets.ResourceResolver;

/**
 * To register this resource resolver, add the following to your web.xml
 * also check if org.deltaset.common.faces.module.DeltasetViewHandler is properly registered
 * <context-param>
 *   <param-name>javax.faces.FACELETS_RESOURCE_RESOLVER</param-name>
 *   <param-value>org.deltaset.common.faces.module.ClasspathResourcerResolver</param-value>
 * </context-param>
 * 
 * @author dmakariev
 */
public class ClasspathResourcerResolver extends ResourceResolver {
    
    private final ResourceResolver defaultResourceResolver;
    
    public ClasspathResourcerResolver(ResourceResolver defaultResourceResolver) {
        this.defaultResourceResolver = defaultResourceResolver;
    }
    
    @Override
    public URL resolveUrl(final String incomingPath) {
        final UrlCache cache = UrlCache.INSTANCE;
        if (cache.containsKey(incomingPath)) {
            return cache.get(incomingPath);
        }
        
        final String path = preparePath(incomingPath);
        
        final URL classpathUrl = Thread.currentThread().getContextClassLoader().getResource(path);
        if (null != classpathUrl) {
            cache.put(incomingPath, classpathUrl);
            return classpathUrl;
        }
        
        
        final URL contextUrl = this.defaultResourceResolver.resolveUrl(incomingPath);
        if (null != contextUrl) {
            cache.put(incomingPath, contextUrl);
        }
        return contextUrl;
    }
    
    private static String preparePath(final String path) {
        /* classpath resources don't start with / */
        if (path.startsWith("/META-INF/")) {
            return path.substring(1);
        } else if (path.startsWith("/")) {
            return "META-INF/" + path.substring(1); //TODO: check and define.. if xhtml-s should stay under META-INF or not
        } else {
            return path;
        }
    }
}
